import React, { useRef, useState } from 'react';
import { PlusOutlined, EllipsisOutlined } from '@ant-design/icons';
import {
  Button,
  Modal,
  Form,
  Input,
  DatePicker,
  Divider,
  message,
  Select,
  Popconfirm,
} from 'antd';
import type { ActionType } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import locale from 'antd/es/date-picker/locale/zh_CN';
import { motifColumns } from './data';
import type { MotifItem } from './data.d';
import TableTitle from '@/components/TableTitle';
import ViewModal from './ViewModal';
import { getVoteList, createVote, publishVote, delVote } from './services';
import moment from 'moment';

const { RangePicker } = DatePicker;
const { Option } = Select;
const { TextArea } = Input;

const VotingManagement = () => {
  // 控制新增、修改投票模态框显示
  const [isProposalModalVisible, setIsProposalModalVisible] = useState(false);
  // 控制新增、修改投票模态框标题
  const [proposalModalTitle, setProposalModalTitle] = useState(true);
  // 控制投票详情模态框显示
  const [isViewModalVisible, setIsViewModalVisible] = useState(false);
  // 查看的数据
  const [viewInfo, setViewInfo] = useState<MotifItem>();
  // 新增/修改
  const [isCreate, setIsCreate] = useState<boolean>(true);

  /**
   * 点击查看调用
   */
  const handleView = (record: MotifItem) => {
    setViewInfo(record);
    setIsViewModalVisible(true);
  };

  const handleEditModel = (record: MotifItem) => {
    setIsProposalModalVisible(true);
    setProposalModalTitle(false);
    setIsCreate(false);
    setViewInfo(record);
    let time = [
      moment(record.startTime, 'YYYY-MM-DD'),
      moment(record.endTime, 'YYYY-MM-DD'),
    ];
    proposalForm.setFieldsValue({ ...record, time });
  };

  const confirmDel = async (serialNo: string) => {
    let res = await delVote({ serialNo });
    console.log(res);
    if (res.code !== '000000') return message.success('删除失败！');
    message.success('删除成功！');
    actionRef.current?.reload();
  };

  // 定义操作单元格
  const columnsOptionRender = (text: any, record: MotifItem) => {
    return [
      <div key={record.serialNo}>
        <a onClick={() => handleView(record)}>配置候选项</a>
        <Divider type="vertical" />
        {record.status == 1 ? (
          <>
            <a onClick={() => handleEditModel(record)}>修改</a>
            <Divider type="vertical" />
            <Popconfirm
              title="是否发布此投票?"
              onConfirm={async () => {
                let res = await publishVote({ serialNo: record.serialNo });
                console.log(res);
                if (res.code !== '000000') return message.success('发布失败！');
                message.success('发布成功！');
                actionRef.current?.reload();
              }}
              onCancel={() => {
                message.warning(`取消发布`);
              }}
              okText="是"
              cancelText="否"
            >
              <a>发布</a>
            </Popconfirm>
            <Divider type="vertical" />
            <Popconfirm
              title="是否删除此条数据?"
              onConfirm={() => confirmDel(record.serialNo)}
              onCancel={() => {
                message.warning(`取消删除`);
              }}
              okText="是"
              cancelText="否"
            >
              <a>删除</a>
            </Popconfirm>
          </>
        ) : null}
      </div>,
    ];
  };

  // 列渲染样式赋值
  motifColumns.forEach((item) => {
    item.dataIndex === 'action'
      ? (item.render = columnsOptionRender)
      : undefined;
  });

  /**
   * 打开新增、修改投票模态框调用
   */
  const showProposalModal = () => {
    setIsCreate(true);
    setIsProposalModalVisible(true);
  };

  /**
   * 点击新增、修改投票模态框确定调用
   */
  const handleProposalOk = async () => {
    await proposalForm.validateFields();
    let response = proposalForm.getFieldsValue();
    console.log(response);
    const { time } = response;
    response.startTime = time[0].format('YYYY-MM-DD HH:mm:ss');
    response.endTime = time[1].format('YYYY-MM-DD HH:mm:ss');
    console.log(response.startTime, response.endTime);
    delete response.time;
    console.log(response);
    let res = await createVote(response);
    console.log(res);
    if (res.code !== '000000') return message.info('添加失败');
    message.success('添加成功');
    actionRef.current?.reload();
    proposalForm.resetFields();
    setIsProposalModalVisible(false);
  };

  /**
   * 关闭新增、修改投票模态框调用
   */
  const handleProposalCancel = () => {
    setIsProposalModalVisible(false);
    proposalForm.resetFields();
  };
  // 绑定表格
  const actionRef = useRef<ActionType>();
  // 绑定表单
  const [proposalForm] = Form.useForm();
  return (
    <>
      <ProTable<MotifItem>
        headerTitle={<TableTitle title="投票投票" />}
        scroll={{ x: 900 }}
        columns={motifColumns}
        actionRef={actionRef}
        cardBordered
        bordered
        rowKey="serialNo"
        dateFormatter="string"
        search={{
          labelWidth: 'auto',
        }}
        columnsState={{
          persistenceKey: 'motif-table',
          persistenceType: 'localStorage',
        }}
        // 分页相关配置
        pagination={{
          // 初始页面数据条数
          pageSize: 10,
        }}
        toolBarRender={() => [
          <Button
            key="button"
            onClick={() => {
              setProposalModalTitle(true);
              showProposalModal();
            }}
            icon={<PlusOutlined />}
            type="primary"
          >
            新增投票
          </Button>,
        ]}
        // 请求获取的数据
        request={async (params) => {
          console.log(params);

          let res = await getVoteList({ ...params });
          console.log(res);
          console.log('🎉');
          const result = {
            data: res.data,
            total: res.pagination.totalSize,
          };
          return result;
        }}
      />
      {/* 新增、修改投票模态框 */}
      <Modal
        width={600}
        title={proposalModalTitle ? '添加投票' : '修改投票'}
        visible={isProposalModalVisible}
        onOk={handleProposalOk}
        onCancel={handleProposalCancel}
      >
        <Form
          name="basic"
          form={proposalForm}
          labelCol={{ span: 6 }}
          wrapperCol={{ span: 16 }}
          initialValues={{ remember: true }}
          autoComplete="off"
        >
          <Form.Item
            label="投票名称"
            name="name"
            rules={[{ required: true, message: '请填写投票名称!' }]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            label="投票code"
            name="code"
            rules={[{ required: true, message: '请填写投票code!' }]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            label="投票类型"
            name="type"
            rules={[{ required: true, message: '请选择投票类型!' }]}
          >
            <Select disabled={!isCreate} style={{ width: '100%' }}>
              <Option value={1}>评选</Option>
              <Option value={2}>选举</Option>
            </Select>
          </Form.Item>
          <Form.Item
            label="投票方法"
            name="method"
            rules={[{ required: true, message: '请选择投票方法!' }]}
          >
            <Select disabled={!isCreate} style={{ width: '100%' }}>
              <Option value={1}>单选</Option>
              <Option value={2}>多选</Option>
            </Select>
          </Form.Item>
          <Form.Item
            label="投票时间"
            name="time"
            rules={[{ required: true, message: '请选择投票时间!' }]}
          >
            <RangePicker
              showTime={{ format: 'YYYY-MM-DD' }}
              format="YYYY-MM-DD"
              locale={locale}
            />
          </Form.Item>
          <Form.Item
            label="投票描述"
            name="description"
            rules={[{ required: true, message: '请填写投票描述!' }]}
          >
            <TextArea />
          </Form.Item>
        </Form>
      </Modal>
      {/* 查看模态框 */}
      <Modal
        bodyStyle={{ margin: 0, padding: 0 }}
        width={1200}
        title="投票候选项"
        visible={isViewModalVisible}
        onCancel={() => {
          setIsViewModalVisible(false);
        }}
        footer={[]}
      >
        <ViewModal viewInfo={viewInfo} />
      </Modal>
    </>
  );
};

export default VotingManagement;
